package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.cake.bigdata.starter.exception.category.BusinessException;
import com.google.common.base.Stopwatch;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import com.mallcai.bigdata.ladon.service.report.node.ReportSqlNode;
import com.mallcai.bigdata.ladon.service.report.node.ReportSqlNodeFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * 这个规则,用来根据当前上下文来将脚本替换为具体的sql
 * @author feixy
 * @version 1.0
 * @date 2019-07-19 21:03
 */
@Slf4j
@Component
@Order(4500)
public class ReplaceDynamicSqlHandler extends AbstractReportQueryPreHandler {

    public static final Pattern ARRAY_PATTERN = Pattern.compile("^\\[(.*)\\]$",  Pattern.DOTALL | Pattern.CASE_INSENSITIVE);

    @Override
    public void preInternal(ReportQueryContext context) {
        String sql = context.getSql();
        Stopwatch stopwatch = Stopwatch.createStarted();
        ReportSqlNode reportSqlNode = ReportSqlNodeFactory.create(sql);
        String parsedSql = reportSqlNode.toSql(context.getQueryParams());
        if (StringUtils.isBlank(parsedSql)){
            throw new BusinessException("非法的参数,解析后的动态sql为空,请检查动态参数");
        }
        stopwatch.stop();
        log.debug("本次解析动态sql耗时{}毫秒", stopwatch.elapsed(TimeUnit.MILLISECONDS));
        context.setSql(parsedSql);
    }

}
